import $api from '@/common/request/index'
import $helpers from '@/common/utils/helpers.js';
import $store from '@/common/store/index.js';

// #ifdef  MP-WEIXIN || MP-ALIPAY
const accountInfo = uni.getAccountInfoSync();
// #endif
export default {

	// 微信小程序登录
	weiXinAppletLogin() {
		var that = this;
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				// console.log('code:' + JSON.stringify(loginRes));
				// {"errMsg":"login:ok","code":"083Hrx000wvL*******0mXX6v1Hrx0l"}

				uni.showModal({
					title: '提示',
					content: '请授权登录',
					cancelText: '微信登录',
					confirmText: '账号密码',
					cancelColor: '#BEBEBE',
					showCancel: true,
					success(res) {
						// console.log(0);
						// console.log(res);

						//如果用户点击了确定按钮
						if (res.confirm) {
							uni.reLaunch({
								url: '/pages-other/login/login'
							});
						} else if (res.cancel) {
							let params = {
								code: loginRes.code,
							};
							that.getUserInfo(params);
						}
					}
				});
			}
		});
	},

	getUserInfo(params) {
		params.appId = accountInfo.miniProgram.appId;
		$api('applet.login', params).then(res => {
				uni.hideLoading();
				$store.commit("SET_PROMPTS_FOR_LOGIN", false)
				if (res.status == 0) {
					let userInfo = res.data;

					$store.commit("SET_TOKEN", userInfo.token)
					userInfo.token = '';
					$store.commit("SET_USER_INFO", userInfo);

					$helpers.toast("登录成功", 'success', 2000, true, () => {
						//获取所有页面栈实例列表
						let pages = getCurrentPages();
						//当前页页面实例
						let nowPage = pages[pages.length - 1];

						if (nowPage.route.endsWith("pages-other/login/login")) {
							uni.reLaunch({
								url: '/pages/home/home?theStatusOfTheInput=true'
							})
						}

						// console.log("login后onLoad()")
						nowPage.onLoad();
						// console.log("login后onShow()")
						nowPage.onShow();
					})
				} else if (res.status == 10001 || res.status == '10001') {
					// 当前微信未绑定任何账号
					$helpers.toast("当前微信未绑定任何账号", 'none', 5000, true, () => {
						uni.reLaunch({
							url: '/pages/register/register'
						})
					})
					return
				} else {
					getApp().err('登录失败，' + res.msg);
				}
			})
			.catch(() => {
				uni.hideLoading();
			});
	},
}
